package com.qinghe.plant.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qinghe.plant.dao.Model;
import com.qinghe.plant.model.ModelResponsitory;
import com.qinghe.plant.option.ManageOption;
import com.qinghe.plant.util.CodeType;
import com.qinghe.plant.util.ManageTool;
import com.qinghe.plant.util.Response;

@RestController
public class ModelController{
	
	@Autowired
	private ModelResponsitory modelResponsitory;
	
	@RequestMapping(value = "doReadModels", method = {RequestMethod.GET})
    public Response ReadModels(HttpServletRequest request) 
	{
		List<Model> models=modelResponsitory.findAll();		
		String content=JSONArray.toJSONString(models).toString();
		return new Response(CodeType.Success,content,"操作成功");
	}
	
	@RequestMapping(value = "doReadModel", method = {RequestMethod.POST})
    public Response ReadModel(HttpServletRequest request) 
	{
		String id=request.getParameter("id");
		Model model=FindModelById(Integer.parseInt(id));
		return new Response(CodeType.Success,JSONObject.toJSONString(model),"操作成功");
	}
	
	@RequestMapping(value = "doAlterModel", method = {RequestMethod.POST})
	public Response AlterModel(HttpServletRequest request,MultipartFile icon,MultipartFile bundle,MultipartFile video1,MultipartFile video2,MultipartFile video3)
	{
		if (bundle.isEmpty()||icon.isEmpty()) {
			return new Response(CodeType.Failed,null,"更新失败，请选择文件");
		}
		String path = ManageOption.Instant().getModelPath();
		String iconName=icon.getOriginalFilename();
		File iconFile=new File(path+iconName);
		
		String bundleName = bundle.getOriginalFilename();	
		File bundleFile = new File(path + bundleName);
		
		if(bundleFile.exists())
			bundleFile.delete();
		
		if(iconFile.exists())
			iconFile.delete();
		
		String video1Name=null;
		File video1File=null;
		if(!video1.isEmpty())
		{
			video1Name=video1.getOriginalFilename();
			video1File=new File(path+video1Name);
			if(video1File.exists())
				video1File.delete();
		}
		String video2Name=null;
		File video2File=null;
		if(!video2.isEmpty())
		{
			video2Name=video2.getOriginalFilename();
			video2File=new File(path+video2Name);
			if(video2File.exists())
				video2File.delete();
		}
		String video3Name=null;
		File video3File=null;
		if(!video3.isEmpty())
		{
			video3Name=video3.getOriginalFilename();
			video3File=new File(path+video3Name);
			if(video2File.exists())
				video3File.delete();
		}
		
		try 
		{	
			icon.transferTo(iconFile);
			bundle.transferTo(bundleFile);
			if(!video1.isEmpty())
				video1.transferTo(video1File);
			if(!video2.isEmpty())
				video2.transferTo(video2File);
			if(!video3.isEmpty())
				video3.transferTo(video3File);
			Model model=JSONObject.parseObject(request.getParameter("model"),Model.class);
			model= modelResponsitory.save(model);
			return new Response(CodeType.Success,JSONObject.toJSONString(model),"操作成功");
		} catch (IOException e)
		{
			if(iconFile.exists())
				iconFile.delete();
			if(bundleFile.exists())
				bundleFile.delete();		
			if(video1File.exists())
				video1File.delete();
			if(video2File.exists())
				video1File.delete();
			if(video3File.exists())
				video3File.delete();
			return new Response(CodeType.Failed,null,"上传失败，请选择文件");
		}	
	}

	@RequestMapping(value = "doInsertModel", method = {RequestMethod.POST})
	public Response InsertModel(HttpServletRequest request,MultipartFile bundle,MultipartFile icon,MultipartFile video1,MultipartFile video2,MultipartFile video3)
	{	
		if(HasModel(request.getParameter("mid")))
		{
			return new Response(CodeType.Failed,null,"同ID模型已经存在！");
		}
		
		if (bundle.isEmpty()||icon.isEmpty()) {
			return new Response(CodeType.Failed,null,"上传失败，请选择文件");
		}
		String path = ManageOption.Instant().getModelPath();
		String iconName=icon.getOriginalFilename();	
		File iconFile=new File(path+iconName);
		String bundleName = bundle.getOriginalFilename();	
		File bundleFile = new File(path + bundleName);	
		
		String video1Name=null;
		File video1File=null;
		if(!video1.isEmpty())
		{
			video1Name=video1.getOriginalFilename();
			video1File=new File(path+video1Name);
		}
		String video2Name=null;
		File video2File=null;
		if(!video2.isEmpty())
		{
			video2Name=video2.getOriginalFilename();
			video2File=new File(path+video2Name);
		}
		String video3Name=null;
		File video3File=null;
		if(!video3.isEmpty())
		{
			video3Name=video3.getOriginalFilename();
			video3File=new File(path+video3Name);
		}
		
		if(bundleFile.exists()||iconFile.exists())
		{
			return new Response(CodeType.Failed,null,"文件已存在");
		}
		else
		{
			try 
			{		
				icon.transferTo(iconFile);
				bundle.transferTo(bundleFile);
				if(!video1.isEmpty())
					video1.transferTo(video1File);
				if(!video2.isEmpty())
					video2.transferTo(video2File);
				if(!video3.isEmpty())
					video3.transferTo(video3File);
				
				Model model=new Model();
				model.setMid(request.getParameter("mid"));
				model.setName(request.getParameter("name"));
				model.setType(request.getParameter("type"));
				model.setIcon(iconName);
				model.setBundle(bundleName);
				model.setVideo(MessageFormat.format("{0}| {1} |{2}", video1Name, video2Name,video3Name));
				model.setCreator(request.getParameter("creator"));
				model.setTimer(new Date());			
				model= modelResponsitory.save(model);		
						
			
				return new Response(CodeType.Success,JSONObject.toJSONString(model),"操作成功");	
			} catch (IOException e)
			{
				if(iconFile.exists())
					iconFile.delete();
				if(bundleFile.exists())
					bundleFile.delete();		
				if(video1File.exists())
					video1File.delete();
				if(video2File.exists())
					video1File.delete();
				if(video3File.exists())
					video3File.delete();
				return new Response(CodeType.Failed,null,"上传失败，请选择文件");
			}	
		}
	}
	
	@RequestMapping(value = "doDeleteModel", method = {RequestMethod.POST})
	public Response DeleteModel(HttpServletRequest request)
	{
		Model model=JSONObject.parseObject(request.getParameter("model"),Model.class);
		modelResponsitory.deleteById(model.getId());
		String iconPath=ManageOption.Instant().getModelPath()+model.getIcon();
		File iconFile=new File(iconPath);
		if(iconFile.exists())
			iconFile.delete();
		
		String bundlePath = ManageOption.Instant().getModelPath()+model.getBundle();		
		File bundleFile = new File(bundlePath);
		if(bundleFile.exists())
			bundleFile.delete();
		
		String[] videos=model.getVideo().split("\\|");
		String video1Path=ManageOption.Instant().getModelPath()+videos[0];
		File video1File=new File(video1Path);
		if(video1File.exists())
			video1File.delete();
		
		String video2Path=ManageOption.Instant().getModelPath()+videos[1];
		File video2File=new File(video2Path);
		if(video2File.exists())
			video2File.delete();
		
		String video3Path=ManageOption.Instant().getModelPath()+videos[2];
		File video3File=new File(video3Path);
		if(video3File.exists())
			video3File.delete();
		
		return new Response(CodeType.Success,null,"操作成功");
	}
	
	@RequestMapping(value="doDownloadModel",method= {RequestMethod.POST})
	public void DownloadModel(HttpServletRequest request, HttpServletResponse response) throws IOException
	{		 
		String fileName=request.getParameter("fileName");
		String filePath=ManageOption.Instant().getModelPath();
		
		//获取输出流
        OutputStream out=response.getOutputStream();
        //把文件变成byte字节流传入输出流
        out.write(ManageTool.GetBytes(filePath+fileName));
        //刷新流
        out.flush();
        //关闭流
        out.close();
        //向控制台提示成功
        System.out.println("success!");
 
    }	
		
	@SuppressWarnings("unused")
	private boolean HasModel(String  mid ) {
		@SuppressWarnings("serial")
		List<Model> result = modelResponsitory.findAll(new Specification<Model>() {
			@Override
			public Predicate toPredicate(Root<Model> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();

				list.add(cb.equal(root.get("mid").as(String.class), mid));
				Predicate[] p = new Predicate[list.size()];
				return cb.and(list.toArray(p));
			}
		});
		return (result.size()!=0)?true:false;
	}
	
	private Model FindModelById(Integer id) {
		@SuppressWarnings("serial")
		List<Model> result = modelResponsitory.findAll(new Specification<Model>() {
			@Override
			public Predicate toPredicate(Root<Model> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();

				list.add(cb.equal(root.get("id").as(Integer.class), id));
				Predicate[] p = new Predicate[list.size()];
				return cb.and(list.toArray(p));
				}
		});
		return (result.size()!=0)?result.get(0):null;
	}
		
}
